package ru.isys.yoomee.ui;

import java.util.ArrayList;
import java.util.List;

import ru.isys.yoomee.R;
import ru.isys.yoomee.model.Chat;
import ru.isys.yoomee.model.ChatItem;
import ru.isys.yoomee.model.Yoo;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ChatsNowActivity extends Activity
{

    public static final String CHATS_NOW_CHAT = "chats_now_chat";
    private Chat mChat;
    private ArrayList<Yoo> mYoos;
    private ArrayList<ChatItem> mChatItems;
    private Gallery mGallery;
    private EditText mNewMessageText;
    private ImageButton mSendMessageButton;
    private ListView mChatList;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        Bundle extras;
        if ((extras = getIntent().getExtras()) == null)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.chats_now_layout);
            mockModelWithoutExtras();

        }
        else
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.chats_now_layout);
            mChat = (Chat) extras.getSerializable(CHATS_NOW_CHAT);
            mYoos = mChat.getYoos();
            mockChatItems();
        }

        mGallery = (Gallery) findViewById(R.id.gallery);
        mGallery.setAdapter(new ChatParticipantsAdapter(this, mYoos));

        mChatList = (ListView) findViewById(android.R.id.list);
        mChatList.setAdapter(new ChatMessagesAdapter(this, R.layout.chats_now_list_item, mChatItems));

        mNewMessageText = (EditText) findViewById(R.id.chats_now_new_text);
        setNewTextMessageListeners(mGallery, mNewMessageText);

        mSendMessageButton = (ImageButton) findViewById(R.id.chats_now_new_send_button);
        mSendMessageButton.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                createNewMessage(mNewMessageText.getText());
                mNewMessageText.setText("");

            }
        });
    }

    private void setNewTextMessageListeners(final Gallery gallery, final EditText newMessageText)
    {
        final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        newMessageText.setOnKeyListener(new OnKeyListener()
        {
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {

                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
                {
                    if (gallery != null && !gallery.isShown())
                    {
                        gallery.setVisibility(View.VISIBLE);
                    }

                    createNewMessage(mNewMessageText.getText());
                    mNewMessageText.setText("");
                    imm.hideSoftInputFromWindow(newMessageText.getWindowToken(), 0);

                    return true;
                }
                return false;
            }
        });

        newMessageText.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                if (gallery != null && gallery.isShown())
                {
                    gallery.setVisibility(View.GONE);
                }
                imm.showSoftInput(newMessageText, InputMethodManager.SHOW_FORCED);
            }
        });

        newMessageText.setOnFocusChangeListener(new OnFocusChangeListener()
        {

            @Override
            public void onFocusChange(View v, boolean hasFocus)
            {
                if (hasFocus)
                {
                    if (gallery != null && gallery.isShown())
                    {
                        gallery.setVisibility(View.GONE);
                    }
                    imm.showSoftInput(newMessageText, InputMethodManager.SHOW_FORCED);
                    mChatList.setSelection(mChatItems.size() - 1);
                }
            }
        });
    }

    protected void createNewMessage(Editable text)
    {
        ChatItem chatItem = new ChatItem(mChat, text.toString(), mChat.getOwner());
        mChatItems.add(chatItem);
        ((ChatMessagesAdapter) mChatList.getAdapter()).notifyDataSetChanged();
        mChatList.setSelection(mChatItems.size());
    }

    private void mockChatWithoutExtras()
    {

        mChat = new Chat(mYoos.get(0).getNickName());

    }

    private void mockYoosWithoutExtras()
    {
        mYoos = new ArrayList<Yoo>();
        mYoos.add(new Yoo("Groupon", 12, 31, false));
        mYoos.add(new Yoo("FourSquare"));
        mYoos.add(new Yoo("Facebook"));
        mYoos.add(new Yoo("IBM"));
        mYoos.add(new Yoo("Starbucks"));

    }

    private void mockChatItemsWithoutExtras()
    {
        mChatItems = new ArrayList<ChatItem>();
        mChatItems.add(new ChatItem(mChat, "Hello", mYoos.get(0)));
        mChatItems.add(new ChatItem(mChat, "Hi", mYoos.get(1)));
        mChatItems.add(new ChatItem(mChat, "Come with me", mYoos.get(0)));
        mChatItems.add(new ChatItem(mChat, "Wut???", mYoos.get(1)));
        mChatItems.add(new ChatItem(mChat, "Hey, wut u need from her", mYoos.get(3)));
        mChatItems.add(new ChatItem(mChat, "Nothin", mYoos.get(0)));
        mChatItems.add(new ChatItem(mChat, "Get out", mYoos.get(3)));
        mChatItems.add(new ChatItem(mChat, "Nice", mYoos.get(2)));
        mChatItems.add(new ChatItem(mChat, "Really", mYoos.get(4)));
    }

    private void mockChatItems()
    {
        mChatItems = new ArrayList<ChatItem>();
        mChatItems.add(new ChatItem(mChat, "Hi", mChat.getOwner()));
        for (Yoo yoo : mYoos)
        {
            mChatItems.add(new ChatItem(mChat, "Hello", yoo));
        }

    }

    private void mockModelWithoutExtras()
    {
        mockYoosWithoutExtras();
        mockChatWithoutExtras();
        mockChatItemsWithoutExtras();
    }

    public class ChatMessagesAdapter extends ArrayAdapter<ChatItem>
    {

        Context mContext;
        List<ChatItem> mListOfChatItems;
        View mView;
        TextView mNickName;
        TextView mDate;
        TextView mTime;
        TextView mMessage;

        public ChatMessagesAdapter(Context context, int textViewResourceId, List<ChatItem> objects)
        {
            super(context, textViewResourceId, objects);
            mContext = context;
            mListOfChatItems = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            mView = convertView;
            ChatItem targetChatItem = mListOfChatItems.get(position);
            if (mView == null)
            {
                mView = getLayoutInflater().inflate(R.layout.chats_now_list_item, null);
            }

            mNickName = (TextView) mView.findViewById(R.id.chat_now_nickname);
            mDate = (TextView) mView.findViewById(R.id.chat_now_date);
            mTime = (TextView) mView.findViewById(R.id.chat_now_time);
            mMessage = (TextView) mView.findViewById(R.id.chat_now_message);

            if (mNickName != null)
            {
                mNickName.setText(targetChatItem.getOwner().getNickName());

            }

            if (mDate != null)
            {
                mDate.setText(targetChatItem.getDate().getDate() + "/" + targetChatItem.getDate().getMonth() + "/"
                        + (1900 + targetChatItem.getDate().getYear()));
            }
            if (mTime != null)
            {
                mTime.setText(targetChatItem.getDate().getHours() + ":" + targetChatItem.getDate().getMinutes());
            }

            if (mMessage != null)
            {
                mMessage.setText(targetChatItem.getMessage());
            }
            return mView;
        }

    }

    public class ChatParticipantsAdapter extends BaseAdapter
    {

        private Context mContext;
        private ArrayList<Yoo> mYoos;
        private TextView mNickname;
        private LayoutInflater mLayoutInflater;
        private int mGalleryItemBackground;

        public ChatParticipantsAdapter(Context context, ArrayList<Yoo> mYoos)
        {
            this.mContext = context;
            this.mYoos = mYoos;
            TypedArray attr = mContext.obtainStyledAttributes(R.styleable.chats_now_top_list_avatars);
            mGalleryItemBackground = attr.getResourceId(R.styleable.chats_now_top_list_avatars_android_galleryItemBackground, 0);
            attr.recycle();
        }

        @Override
        public int getCount()
        {

            return mYoos.size();
        }

        @Override
        public Object getItem(int position)
        {

            return mYoos.get(position);
        }

        @Override
        public long getItemId(int position)
        {

            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            Log.v("TAG", "getView");

            View view;
            if (convertView == null)
            { // if it's not recycled, initialize some attributes

                view = getLayoutInflater().inflate(R.layout.chats_now_top_list_avatar, null);

            }
            else
            {
                view = (View) convertView;
            }

            ImageView image = (ImageView) view.findViewById(R.id.chats_now_avatar);

            Drawable drawable = getResources().getDrawable(R.id.yoo_avatar);
            Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.yoo_avatar);
            Canvas canvas = new Canvas();

            Bitmap bitmapResult = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas();
            c.setBitmap(bitmapResult);

            c.drawBitmap(bm, 0, 0, null);

            Paint paint = new Paint();
            paint.setColor(Color.WHITE);
            paint.setAntiAlias(true);
            paint.setTextSize(14);
            c.drawText("NickName", 10, 25, paint);

            image.setImageBitmap(bitmapResult);
            image.setLayoutParams(new Gallery.LayoutParams(100, 100));
            image.setScaleType(ImageView.ScaleType.FIT_XY);
            image.setBackgroundResource(mGalleryItemBackground);

            Yoo yoo = mYoos.get(position);

            return image;
        }

    }
}
